package cn.calm.template;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;

import org.apache.log4j.Logger;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;

import cn.calm.commons.dao.IBaseDao;
import cn.calm.entity.Template;
import cn.calm.template.service.ITemplateService;
import cn.calm.template.service.impl.TemplateServiceImpl;

public class Activator implements BundleActivator {
	public BundleContext context;
	private static final Logger log = Logger.getLogger(Activator.class);
	@SuppressWarnings("rawtypes")
	ServiceRegistration<ITemplateService> sr;

	@Override
	public void start(BundleContext context) throws Exception {
		log.debug("starting");
		try {
			this.context = context;
			ServiceReference<IBaseDao> serviceRef = context
					.getServiceReference(IBaseDao.class);
			IBaseDao dao = context.getService(serviceRef);
			ITemplateService<Template> templateService = new TemplateServiceImpl<Template>();
			EntityManager em = Persistence.createEntityManagerFactory("entity")
					.createEntityManager();
			dao.setSession(em);
			templateService.setBaseDao(dao);
			sr = context.registerService(ITemplateService.class,
					templateService, null);
			
		} catch (Exception e) {
			log.error("", e);
		} finally {
			log.debug("started");
		}

	}

	@Override
	public void stop(BundleContext arg0) throws Exception {
		if (sr != null) {
			sr.unregister();
		}
	}

}
